<template>
  <div>
    <!-- 航班信息 -->
    <el-card class="flight-info" shadow style="float: right; margin-left: 20px;width: auto;">
      <div slot="header" class="clearfix" style>
        <span>航班信息</span>
      </div>
      <div>
        <div>
          <span>{{formatDate(flight.departureTime)}}&nbsp;&nbsp;&nbsp; {{flight.cityFrom}}&nbsp;-&nbsp;{{flight.cityTo}}</span>
        </div>

        <div>
          <span style="font-size: 10px; color:#C0C4CC;">{{flight.airline}} {{flight.flightNumber}}</span>
          <span style="float: right;font-size: 10px; color:#C0C4CC;">{{ flight.cabin }}</span>
        </div>
        <div style="margin-top: 20px;">
          <div style="margin-top: 2px;float: left; height: 50px; width: auto;">
            <div>{{formatTime(flight.departureTime)}}</div>
            <div style="font-size: 10px;">{{ flight.departureAirport }}</div>
          </div>
          <div
            style="height: 50px;line-height: 50px;float: left; text-align: center; width: auto; margin: 0 30px;"
          >
            <span
              style=" font-size: 10px;color:#C0C4CC;"
            >--{{timeInterval(flight.departureTime,flight.arrivalTime)}}--</span>
          </div>
          <div style="height:50px;float: right; width: auto;">
            <div>{{formatTime(flight.arrivalTime)}}</div>
            <div style="font-size: 10px;">{{ flight.arrivalAirport }}</div>
          </div>
        </div>
      </div>
      <div style="float: left;width: 100%;">
        <el-divider></el-divider>
        <span
          style="float: right; margin-top: -15px; margin-bottom: 15px;"
        >合计：{{flight.price * orderForm.passengers.length }}</span>
      </div>
    </el-card>
    <el-form :model="orderForm">
      <el-form-item>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>联系人</span>
          </div>
          <div>
            <el-autocomplete
              v-model="orderForm.contact.contactName"
              :fetch-suggestions="querySearch"
              placeholder="姓名"
            ></el-autocomplete>
            <el-input
              v-model="orderForm.contact.contactPhone"
              placeholder="手机号"
              style="margin-top: 18px;"
            ></el-input>
            <el-input
              v-model="orderForm.contact.contactEmail"
              placeholder="邮箱（选填）"
              style="margin-top: 18px;"
            ></el-input>
          </div>
        </el-card>
      </el-form-item>
      <el-form-item>
        <!-- 乘机人 -->
        <el-card class="box-card">
          <div slot="header" class="clearfix" style>
            <span>乘机人信息</span>
            <el-button
              type="text"
              icon="el-icon-plus"
              @click="addPassenger"
              style="
                  float: right;
                  display: inline-block;
                  vertical-align: middle;
                "
            >添加乘机人</el-button>
          </div>

          <!-- 乘机人卡片内容部分 -->
          <div v-for="(passenger, index) in orderForm.passengers" :key="index">
            <div>
              <el-row>
                <el-col :span="2" :offset="22">
                  <el-button icon="el-icon-circle-close" @click="removePassenger(index)" />
                </el-col>
              </el-row>
            </div>

            <div>
              <el-row>
                <el-col :span="4">
                  <span>姓名：</span>
                </el-col>
                <el-col :span="20">
                  <el-autocomplete
                    v-model="passenger.paxName"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入乘机人姓名"
                  ></el-autocomplete>
                </el-col>
              </el-row>
            </div>

            <!-- 身份证件信息输入框 -->
            <div style="margin-top: 10px" class="my-identity">
              <el-row>
                <el-col :span="4">
                  <span>身份信息：</span>
                </el-col>
                <el-col :span="20">
                  <el-input
                    placeholder="请输入内容身份证号"
                    v-model="passenger.certificateNo"
                    class="input-with-select"
                  >
                    <el-select
                      v-model="passenger.certificateType"
                      slot="prepend"
                      placeholder="证件类型"
                      class="select-id-type"
                    >
                      <el-option label="身份证" value="1"></el-option>
                      <el-option label="护照" value="2"></el-option>
                      <el-option label="港澳通行证" value="3"></el-option>
                      <el-option label="台湾通行证" value="4"></el-option>
                    </el-select>
                  </el-input>
                </el-col>
              </el-row>
            </div>
            <el-divider></el-divider>
          </div>
        </el-card>
      </el-form-item>
      <el-form-item>
        <div>
          <el-button @click="cancelDig">取消</el-button>
          <el-button type="primary" @click="submitOrder">去支付</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      num: "",
      dialogVisible: false,
      orderForm: {
        flightId: "",
        cabinId: "",
        contact: {
          contactName: "",
          contactPhone: "",
          contactEmail: "",
        },
        buyNumber: 1,
        price: "",
        passengers: [{ paxName: "", certificateNo: "", certificateType: "" }],
      },
      flight: {},

      contacts: [
        { value: "三全鲜食（北新泾店）" },
        { value: "三全鲜食（北新泾店）" },
        { value: "三全鲜食（北新泾店）" },
      ], // 假设这是联系人列表
    };
  },
  methods: {
    // 提交订单
    async submitOrder() {
      // TODO: 实现提交订单的逻辑
      if (
        this.isNullOrEmpty(this.orderForm.contact.contactName) ||
        this.isNullOrEmpty(this.orderForm.contact.contactPhone)
      ) {
        this.$message.warning("请正确填写联系人信息");
        return;
      }
      const isTrue = this.orderForm.passengers.every((p) => {
        return p.paxName && p.certificateType && p.certificateNo;
      });
      if (!isTrue) {
        this.$message.warning("请正确填写乘机人信息");
        return;
      }
      if (this.orderForm.buyNumber <= 0) {
        this.$message.warning("请输入乘机人");
        return;
      }

      await this.$axios
        .post("/api/orders/add", this.orderForm)
        .then((res) => {
          if (res.data.code === 1) {
            this.$confirm("确定支付吗？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                // 用户点击了确定按钮后执行的操作
                this.pay(res.data.data);
              })
              .catch(() => {
                // 用户点击了取消按钮后执行的操作
                this.$message.warning("请尽快支付");
              });
            this.orderForm.contact = {
              contactName: "",
              contactPhone: "",
              contactEmail: "",
            };
            this.orderForm.passengers = [
              { paxName: "", certificateNo: "", certificateType: "" },
            ];
            this.cancelDig("succ");
          } else if (res.data.code === 0) {
            this.$message.error(res.data.msg);
          }
        })
        .catch((error) => {
          // 处理请求失败的错误
          this.$message.error(error.response.data.msg);
        });
    },
    async pay(data) {
      await this.$axios
        .put("/api/orders/pay/" + data)
        .then((res) => {
          if (res.data.code === 1) {
            this.$message.success(res.data.msg);
          } else {
            this.$message.error("支付失败");
          }
        })
        .catch((error) => {
          this.$message.error(error.response.data.msg);
        });
    },
    isNullOrEmpty(str) {
      return str == null || str.trim() === "";
    },
    price(value) {
      if (!value) {
        return "-";
      }
      const cabin = value.find((cabin) => cabin.name === "经济舱");
      return cabin.price;
    },
    // 添加乘机人
    addPassenger() {
      this.orderForm.passengers.push({
        name: "",
        idType: "",
        idNumber: "",
        phone: "",
      });
      this.orderForm.buyNumber = this.orderForm.passengers.length;
    },
    // 移除乘机人
    removePassenger(index) {
      console.log(index);
      this.orderForm.passengers.splice(index, 1);
    },
    cancelDig() {
      this.$emit("my-event", false);
    },
    // 根据输入查询联系人或乘机人建议列表
    querySearch(queryString, cb) {
      const results = queryString
        ? this.contacts.filter((contact) => contact.indexOf(queryString) === 0)
        : this.contacts;
      cb(results);
    },
    // 格式化时间
    formatDate(dateString) {
      // 构造日期对象
      const date = new Date(dateString);

      // 获取月份和日期并组合成新字符串
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const formattedDate = `${month}-${day}`;

      return formattedDate;
    },
    formatTime(dateString) {
      const date = new Date(dateString);
      const time = date.toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
      });

      return time;
    },
    timeInterval(time1, time2) {
      const start = new Date(time1); // 当前时间
      const end = new Date(time2);

      const interval = end.getTime() - start.getTime(); // 计算时间间隔的毫秒数

      const hours = Math.floor(interval / (1000 * 60 * 60)); // 将毫秒数转换为小时数，取整
      const minutes = Math.floor(interval % (1000 * 60)); // 将毫秒数转换为分钟数，取整
      return `${hours}h${minutes}m`;
    },
  },
  mounted() {
    this.$bus.$on("flight", (data) => {
      this.flight = data;
      this.orderForm.flightId = data.id;
      this.orderForm.cabinId = data.cabinId;
      this.orderForm.price = data.price;
    });
  },
  beforeDestroy() {
    this.$bus.$off("flight");
  },
};
</script>
<style scoped>
/* 卡片样式 */
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.box-card >>> .el-card__header {
  padding: 8px 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.box-card {
  width: auto;
}

/* 身份信息输入框样式 */
.select-id-type {
  width: 110px;
}
.input-with-select {
  width: 380px;
}

.my-identity >>> .el-input-group__prepend {
  background-color: #fff;
}
/* 航班信息样式 */
.flight-info {
  margin-bottom: 20px;
}
</style>
